import { Request, Response } from 'express';
import { fileService } from '../services/fileService';
import { CreateAgentInput, UpdateAgentInput, PaginationQuery, ApiResponse } from '../types/agent';

/**
 * 智能体控制器类
 */
export class AgentController {
  /**
   * 获取所有智能体（支持分页和搜索）
   */
  async getAllAgents(req: Request, res: Response): Promise<any> {
    try {
      const query: PaginationQuery = {
        page: parseInt(req.query.page as string) || 1,
        limit: parseInt(req.query.limit as string) || 10,
        category: req.query.category as string,
        search: req.query.search as string,
        tags: req.query.tags ? (req.query.tags as string).split(',') : undefined
      };

      const result = await fileService.getAgentsPaginated(query);
      
      const response: ApiResponse = {
        success: true,
        data: result
      };
      
      res.json(response);
      return response;
    } catch (error) {
      console.error('Error getting agents:', error);
      const errorResponse: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : 'Internal server error'
      };
      res.status(500).json(errorResponse);
      return errorResponse;
    }
  }

  /**
   * 根据ID获取智能体
   */
  async getAgentById(req: Request, res: Response): Promise<any> {
    try {
      const { id } = req.params;
      
      if (!id) {
        const response: ApiResponse = {
          success: false,
          error: 'Agent ID is required'
        };
        res.status(400).json(response);
        return;
      }

      const agent = await fileService.getAgentById(id);
      
      if (!agent) {
        const errorResponse = {
          success: false,
          error: 'Agent not found'
        };
        res.status(404).json(errorResponse);
        return null;
      }
      
      const response = {
        success: true,
        data: agent
      };
      res.json(response);
      return agent;
    } catch (error) {
      console.error('Error getting agent by ID:', error);
      const errorResponse = {
        success: false,
        error: 'Failed to get agent'
      };
      res.status(500).json(errorResponse);
      return null;
    }
  }

  /**
   * 创建新智能体
   */
  async createAgent(req: Request, res: Response): Promise<void> {
    try {
      const agentData: CreateAgentInput = req.body;
      
      // 调试日志：记录接收到的数据
      console.log('后端接收到的智能体数据:', JSON.stringify(agentData, null, 2));
      
      // 验证必需字段（description和usage是可选的）
      const requiredFields = ['name', 'author', 'version', 'category', 'shareUrl'];
      const missingFields = requiredFields.filter(field => {
        const value = agentData[field as keyof CreateAgentInput];
        return !value || (typeof value === 'string' && value.trim() === '');
      });
      
      // 调试日志：记录字段验证结果
      console.log('字段验证结果:', {
        requiredFields,
        missingFields,
        fieldValues: requiredFields.reduce((acc, field) => {
          acc[field] = agentData[field as keyof CreateAgentInput];
          return acc;
        }, {} as any)
      });
      
      if (missingFields.length > 0) {
        const response: ApiResponse = {
          success: false,
          error: `Missing required fields: ${missingFields.join(', ')}`
        };
        res.status(400).json(response);
        return;
      }
      
      // 确保可选字段有默认值
      if (!agentData.description) {
        agentData.description = '';
      }
      
      if (!agentData.usage) {
        agentData.usage = '';
      }
      
      // 确保tags是数组
      if (!Array.isArray(agentData.tags)) {
        agentData.tags = [];
      }
      
      // 确保config是对象
      if (!agentData.config || typeof agentData.config !== 'object') {
        agentData.config = {};
      }
      
      const result = await fileService.createAgent(agentData);
      
      if (result.success) {
        const response: ApiResponse = {
          success: true,
          data: result.data,
          message: result.message
        };
        res.status(201).json(response);
      } else {
        const response: ApiResponse = {
          success: false,
          error: result.error
        };
        res.status(400).json(response);
      }
    } catch (error) {
      console.error('Error creating agent:', error);
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : 'Internal server error'
      };
      res.status(500).json(response);
    }
  }

  /**
   * 更新智能体
   */
  async updateAgent(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      const updateData: UpdateAgentInput = req.body;
      
      if (!id) {
        const response: ApiResponse = {
          success: false,
          error: 'Agent ID is required'
        };
        res.status(400).json(response);
        return;
      }
      
      // 确保tags是数组（如果提供）
      if (updateData.tags && !Array.isArray(updateData.tags)) {
        updateData.tags = [];
      }
      
      // 确保config是对象（如果提供）
      if (updateData.config && typeof updateData.config !== 'object') {
        updateData.config = {};
      }
      
      const result = await fileService.updateAgent(id, updateData);
      
      if (result.success) {
        const response: ApiResponse = {
          success: true,
          data: result.data,
          message: result.message
        };
        res.json(response);
      } else {
        const statusCode = result.error === 'Agent not found' ? 404 : 400;
        const response: ApiResponse = {
          success: false,
          error: result.error
        };
        res.status(statusCode).json(response);
      }
    } catch (error) {
      console.error('Error updating agent:', error);
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : 'Internal server error'
      };
      res.status(500).json(response);
    }
  }

  /**
   * 删除智能体
   */
  async deleteAgent(req: Request, res: Response): Promise<void> {
    try {
      const { id } = req.params;
      
      if (!id) {
        const response: ApiResponse = {
          success: false,
          error: 'Agent ID is required'
        };
        res.status(400).json(response);
        return;
      }
      
      const result = await fileService.deleteAgent(id);
      
      if (result.success) {
        const response: ApiResponse = {
          success: true,
          data: result.data,
          message: result.message
        };
        res.json(response);
      } else {
        const statusCode = result.error === 'Agent not found' ? 404 : 400;
        const response: ApiResponse = {
          success: false,
          error: result.error
        };
        res.status(statusCode).json(response);
      }
    } catch (error) {
      console.error('Error deleting agent:', error);
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : 'Internal server error'
      };
      res.status(500).json(response);
    }
  }

  /**
   * 获取智能体统计信息
   */
  async getAgentStats(req: Request, res: Response): Promise<void> {
    try {
      const stats = await fileService.getAgentStats();
      
      const response: ApiResponse = {
        success: true,
        data: stats
      };
      
      res.json(response);
    } catch (error) {
      console.error('Error getting agent stats:', error);
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : 'Internal server error'
      };
      res.status(500).json(response);
    }
  }

  /**
   * 导出智能体数据
   */
  async exportAgents(req: Request, res: Response): Promise<void> {
    try {
      const agents = await fileService.exportData();
      
      // 设置下载头
      const timestamp = new Date().toISOString().split('T')[0];
      const filename = `agents-export-${timestamp}.json`;
      
      res.setHeader('Content-Type', 'application/json');
      res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
      
      res.json(agents);
    } catch (error) {
      console.error('Error exporting agents:', error);
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : 'Internal server error'
      };
      res.status(500).json(response);
    }
  }

  /**
   * 导入智能体数据
   */
  async importAgents(req: Request, res: Response): Promise<void> {
    try {
      const agents = req.body;
      
      if (!Array.isArray(agents)) {
        const response: ApiResponse = {
          success: false,
          error: 'Invalid data format: expected array of agents'
        };
        res.status(400).json(response);
        return;
      }
      
      const result = await fileService.importData(agents);
      
      if (result.success) {
        const response: ApiResponse = {
          success: true,
          data: result.data,
          message: result.message
        };
        res.json(response);
      } else {
        const response: ApiResponse = {
          success: false,
          error: result.error
        };
        res.status(400).json(response);
      }
    } catch (error) {
      console.error('Error importing agents:', error);
      const response: ApiResponse = {
        success: false,
        error: error instanceof Error ? error.message : 'Internal server error'
      };
      res.status(500).json(response);
    }
  }

  /**
   * 获取统计信息
   */
  async getStats(req: Request, res: Response): Promise<any> {
    try {
      const stats = await fileService.getStats();
      const response = {
        success: true,
        data: stats
      };
      res.json(response);
      return response;
    } catch (error) {
      const errorResponse = {
        success: false,
        error: 'Failed to get stats'
      };
      res.status(500).json(errorResponse);
      return errorResponse;
    }
  }

  /**
   * 导出数据
   */
  async exportData(req: Request, res: Response): Promise<any> {
    try {
      const data = await fileService.exportData();
      const response = {
        success: true,
        data,
        filename: `agents_export_${new Date().toISOString().split('T')[0]}.json`
      };
      res.json(response);
      return response;
    } catch (error) {
      const errorResponse = {
        success: false,
        error: 'Failed to export data'
      };
      res.status(500).json(errorResponse);
      return errorResponse;
    }
  }

  /**
   * 导入数据
   */
  async importData(req: Request, res: Response): Promise<any> {
    try {
      const { agents } = req.body;
      if (!agents || !Array.isArray(agents)) {
        const errorResponse = {
          success: false,
          error: 'Invalid data format: expected array of agents'
        };
        res.status(400).json(errorResponse);
        return errorResponse;
      }

      const result = await fileService.importData(agents);
      const response = {
        success: true,
        data: result
      };
      res.json(response);
      return response;
    } catch (error) {
      const errorResponse = {
        success: false,
        error: 'Failed to import data'
      };
      res.status(500).json(errorResponse);
      return errorResponse;
    }
  }

  /**
   * 数据迁移
   */
  async migrateData(req: Request, res: Response): Promise<any> {
    try {
      // 模拟迁移过程
      const response = {
        success: true,
        data: {
          migrated: true,
          message: 'Data migration completed successfully',
          timestamp: new Date().toISOString()
        }
      };
      res.json(response);
      return response;
    } catch (error) {
      const errorResponse = {
        success: false,
        error: 'Migration failed'
      };
      res.status(500).json(errorResponse);
      return errorResponse;
    }
  }

  /**
   * 健康检查
   */
  async healthCheck(req: Request, res: Response): Promise<any> {
    try {
      const stats = await fileService.getStats();
      const response = {
        success: true,
        data: {
          status: 'healthy',
          timestamp: new Date().toISOString(),
          stats
        }
      };
      res.json(response);
      return response;
    } catch (error) {
      const errorResponse = {
        success: false,
        error: 'Health check failed'
      };
      res.status(500).json(errorResponse);
      return errorResponse;
    }
  }
}

// 导出控制器实例
export const agentController = new AgentController();